# coding=utf-8
from datetime import datetime
from flask import current_app
from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.modules import db
from comment.modules.deal_record import DealRecord
from comment.modules.invest_record import Invest_record
from comment.modules.user import User
from comment.modules.account import Account
from comment.modules.expected_return import Expected_return
from comment.ultils.gen_trans_id import gen_trans_id
from financial.resorces.transaction.const import DealType

from financial.resorces.transaction.serializer import ExpectedReturnPaginateSerializer

class InvestIncomeResource(Resource):
    '''获取某个预期收益到期之后，获得当前的收益'''

    def post(self):
        rp = RequestParser()
        rp.add_argument('return_id')
        args = rp.parse_args()
        return_id = int(args.get('return_id'))

        user_id = g.user_id
        #根据当前的用户查询资金账户对象
        account = Account.query.filter(Account.userId == user_id).first()

        #查询当前指定的预期收益对象
        expected_income = Expected_return.query.filter(Expected_return.id == return_id).first()

        if expected_income:
            #判断当前的预期收益是否可以开始获取收益
            cur_date = datetime.now().date() #获得时间戳
            expected_date = expected_income.expectedDate.date()
            if cur_date >= expected_date: #如果当前日期大于投资到期日期
                try:
                    #查询对应的投资记录对象
                    invest = Invest_record.query.filter(Invest_record.pId == expected_income.investRecord).first()
                    invest.pStatus = 2 #修改投资记录的状态

                    #修改用户的资金账户
                    account.interestA += expected_income.expectedMoney #修改已经赚取的利息
                    account.interestTotal -= expected_income.expectedMoney #总计待收利息
                    account.inverstmentW -= invest.pAmount #总计代收的本金
                    account.frozen -= invest.pAmount #账户总计冻结总额
                    before_balance = account.balance #修改之前的余额
                    account.balance += (invest.pAmount + expected_income.expectedMoney) #修改账户余额
                    account.total += expected_income.expectedMoney #修改帐户总额

                    #新增一条交易记录
                    #生成流水号
                    deal_num = gen_trans_id(DealType.income.name)
                    # 生成交易记录
                    deal_log = DealRecord(aUserId=user_id, aReceiveOrPay=1, aTransferSerialNo=deal_num,
                                          aTransferStatus=1, aBeforeTradingMoney=account.balance,
                                          aAmount=expected_income.expectedMoney, aAfterTradingMoney=account.balance,
                                          aDescreption='提取收益', aType=DealType.income.value)
                    # 将预期收益的可提取金额置为0
                    expected_income.expectedMoney = 0
                    db.session.add(deal_log)
                    db.session.commit()
                    return {'msg':'success'}
                except Exception as e:
                    current_app.logger.error(e)
                    db.session.rollback()
                    return {
                        'message':'系统出错',
                        'code':218
                    }
            else:
                return {
                    'message':'投资未到期',
                    'code':219
                }
        else:
            return {
                'message':'没有找到对于的预期首页',
                'code':220
                }






















